package demo_0714;

import java.util.PriorityQueue;

public class T14_0330 {
    // 选择排序
    public static void selectSort1(int[] array) {
        // write code  here
        for (int i = 0; i < array.length - 1; i++) {
            int min = i;
            for (int j = i; j < array.length; j++) {
                if (array[j] < array[min]) {
                    min = j;
                }
            }
            swap(array, min, i);
        }
    }
    //方法二
    public static void selectSort2(int[] array) {
        int left = 0;
        int right = array.length - 1;
        while (left < right) {
            int mixIndex = left;
            int maxIndex = left;
            for (int i = left; i <= right; i++) {
                if (array[mixIndex] > array[i]) {
                    mixIndex = i;
                }
                if (array[maxIndex] < array[i]) {
                    maxIndex = i;
                }
            }
            swap(array,mixIndex,left);
            if (maxIndex == left) {
                maxIndex = mixIndex;
            }
            swap(array,maxIndex,right);
            left++;
            right--;
        }
    }

    // 堆排序
    public static void heapSort(int[] array){
        // write code  here
        creatBigHeap(array);
        int end = array.length - 1;
        while (end > 0) {
            swap(array,0,end);
            siftDown(array,0,end); //siftDown代码中为length（不包含length），所以传end。
            end--;
        }
    }

    private static void creatBigHeap(int[] array) {
        for (int parent = (array.length - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(array,parent,array.length);
        }
    }

    private static void siftDown(int[] array, int parent, int length) {
        int child = parent * 2 + 1;
        while (child < length) {
            if (child + 1 < length && array[child + 1] > array[child]) {
                child++;
            }
            if (array[child] > array[parent]) {
                swap(array,child,parent);
                parent =child;
                child = parent * 2 + 1;
            }else {
                return;
            }
        }
    }

    //交换
    private static void swap(int[] array,int i,int j) {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

    public static void main(String[] args) {
        int[] array = {42,20,17,13,28,14,23,15};
        heapSort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
        System.out.println();
        int[] array2 = {15,12,13,14,16,17,18,19,10,11};
        selectSort2(array2);
        for (int i = 0; i < array2.length; i++) {
            System.out.print(array2[i] + " ");
        }
        System.out.println();
    }
}
